package net.poddubnyak.friendlist.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import net.poddubnyak.friendlist.domain.User;

/**
 * UserDAOImpl represents DAO for User class.
 * 
 * @author Poddubnjak Petr
 */
@Repository
public class UserDAOImpl implements UserDAO {

	@Autowired
	private SessionFactory sessionFactory;

	/**
	 * Add User to Database
	 * 
	 * @param user
	 */
	public void addUser(User user) {
		sessionFactory.getCurrentSession().save(user);

	}

	/**
	 * Delete User from database
	 * 
	 * @param id
	 *            - id of user
	 */
	public void removeUser(Integer id) {
		User user = (User) sessionFactory.getCurrentSession().load(User.class,
				id);
		if (null != user) {
			sessionFactory.getCurrentSession().delete(user);
		}
	}

	/**
	 * Update record in database
	 * 
	 * @param user
	 *            - wish need to update
	 */
	public void updateUser(User user) {
		sessionFactory.getCurrentSession().update(user);
	}

	/**
	 * Get list of all Users from database
	 * 
	 * @return - list of all users
	 */
	@SuppressWarnings("unchecked")
	public List<User> listUser() {
		return sessionFactory.getCurrentSession().createQuery("from User")
				.list();
	}

	/**
	 * Get list of 5 toprated Users from database
	 * 
	 * @return - list of 5 toprated users.
	 */
	@SuppressWarnings("unchecked")
	public List<User> listTopUsers() {
		Query query = sessionFactory.getCurrentSession().createQuery(
				"from User user order by user.rating desc");
		return query.setMaxResults(5).list();
	}

	/**
	 * Get list of classmates Users from database
	 * 
	 * @param groupId
	 *            - id of group
	 * @return - list of classmates users
	 */
	@SuppressWarnings("unchecked")
	public List<User> listClassmates(String groupId) {
		Query query = sessionFactory.getCurrentSession().createQuery(
				"from User user where user.groupId = :group");
		return query.setParameter("group", groupId).list();
	}

	/**
	 * Gets User from database by id
	 * 
	 * @param id
	 *            - id of User
	 * @return - User
	 */
	public User getUserById(Integer id) {
		return (User) sessionFactory.getCurrentSession()
				.createQuery("from User user where user.id = :userId")
				.setParameter("userId", id).uniqueResult();

	}

	/**
	 * Gets User from database by email
	 * 
	 * @param email
	 *            - addres of users email
	 * @return - User
	 */
	public User getUserByEmail(String email) {
		return (User) sessionFactory.getCurrentSession()
				.createQuery("from User user where user.email = :userEmail")
				.setParameter("userEmail", email).uniqueResult();
	}

}
